<?php
/*
 * 通联支付
 */
namespace app\common\model;
use think\Model;
use think\Db;

class Allinpay extends Model{

    public $url = "http://test.allinpay.com/op/gateway";
    public $appId = "1283233906081939458";
    public $secretKey = "eMDVxpfvt1k8mIiCZvDLWx9wtJcdtVBQ";
    public $privateKeyPath = "1283233906081939458.pfx";
    public $pwd = "939458";
    public $tlPublicKey = "TLCert-test.cer";

    public $config = [
        'serverUrl' =>'http://test.allinpay.com/op/gateway',
        'path'=>'./data/1293840404734611458.pfx',
        'pwd'=>'123456',
        'version'=>'1.0',
        'tlCertPath'=>'./data/TLcert-test-new.cer',
        'appId'=>'1293840404734611458',
        'secretKey' => 'seSAko2cLLC0UgyqAPw5M4HSe3ninEWi',
        'htCertPath'=>'./data/DDW2.pfx', //华通银行提供给商户的私钥证书文件
        'htCertPwd'=>'111111'
    ];

    /**
     * @title
     * @desc createMember
     * @code
     * @author allen
     * @date 2023-02-16 17:33
     */
    //public function createMember(){
    //
    //    $post=[
    //        'appId'=>$this->appId,
    //        'method'=>'allinpay.yunst.memberService.createMember',
    //        'format'=>'JSON',
    //        'charset'=>'utf-8',
    //        'signType'=>'SHA256WithRSA',
    //        'timestamp'=>date('Y-m-d H:i:s',time()),
    //        'version'=>'1.0',
    //        'appAuthToken'=>'',
    //        'bizContent'=>[
    //            'bizUserId'=>'wudi001',
    //            'memberType'=>3,//2-企业，3-个人
    //            'source'=>1//1-mobile,2-pc
    //            //'extendParam'=>[]
    //        ]
    //
    //    ];
    //
    //    $sign='';
    //    $post['sign']=$sign;
    //    $post=http_json($this->url,json_encode($post));
    //
    //
    //}
    /******************************************************************************************************************/
    /****                                           会员类                                                        ******/
    /******************************************************************************************************************/

    public function applyBindBankCard($bizUserId,$cardNo,$phone,$name,$cardCheck,$identityType,$identityNo,$validate=null,$cvv2=null)
    {
        $param = array();
        $yunClient = new yunClient();
        $param["bizUserId"] = $bizUserId;
        $param["cardNo"] = $yunClient->encryptAES($cardNo);
        $param["phone"] = $phone;
        $param["name"] = $name;
        $param["cardCheck"] = $cardCheck;
        $param["identityType"] = $identityType;
        $param["identityNo"] = $yunClient->encryptAES($identityNo);
        $param["validate"] = $yunClient->encryptAES($validate);
        $param["cvv2"] = $yunClient->encryptAES($cvv2);
        $method = "allinpay.yunst.memberService.applyBindBankCard";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }
    /**
     * [createMember 创建会员]
     */
    public function createMember($bizUserId, $memberType = 3, $source = 2)
    {
        $param = array();
        $param["bizUserId"] = $bizUserId;
        $param["memberType"] = $memberType;
        $param["source"] = $source;
        $method = "allinpay.yunst.memberService.createMember";
        $yunClient = new yunClient();
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    /**
     * [setCompanyInfo 设置企业信息]
     */
    public function setCompanyInfo($bizUserId)
    {
        $yunClient = new yunClient();
        $param = array();
        $param["bizUserId"] = $bizUserId;
        $param["backUrl"] = "https://www.baidu.com";
        $companyBasicInfo['companyName'] = '测试';
        $companyBasicInfo['legalName'] = '测试';
        $companyBasicInfo['identityType'] = 1;
        $companyBasicInfo['legalIds'] = $yunClient->encryptAES('140724199411111111');
        $companyBasicInfo['legalPhone'] = '18734893146';
        $companyBasicInfo['accountNo'] = $yunClient->encryptAES('6227000267060250071');
        $companyBasicInfo['parentBankName'] = '建设银行';
        $companyBasicInfo['businessLicense'] = '123456789';
        $companyBasicInfo['organizationCode'] = '123456789';
        $companyBasicInfo['taxRegister'] = '123456789';
        $param["companyBasicInfo"] = $companyBasicInfo;
        $param["isAuth"] = false;
        $method = "allinpay.yunst.memberService.setCompanyInfo";

        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    /**
     * [sendVerificationCode 发送短信验证码]
     */
    public function sendVerificationCode($bizUserId, $phone, $verificationCodeType)
    {
        $param = array();
        $param["bizUserId"] = $bizUserId;
        $param["phone"] = $phone;
        $param["verificationCodeType"] = $verificationCodeType;
        $method = "allinpay.yunst.memberService.sendVerificationCode";
        $yunClient = new yunClient();
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    /**
     * [bindPhone 绑定手机]
     */
    public function bindPhone($bizUserId, $phone, $verificationCode)
    {
        $param = array();
        $param["bizUserId"] = $bizUserId;
        $param["phone"] = $phone;
        $param["verificationCode"] = $verificationCode;
        $method = "allinpay.yunst.memberService.bindPhone";
        $yunClient = new yunClient();
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    /**
     * [signContract 电子会员签约]
     */
    public function signContract($bizUserId,$jumpUrl,$backUrl,$source)
    {
        $param = array();
        $param["bizUserId"] = $bizUserId;
        $param["jumpUrl"] = $jumpUrl;
        $param["backUrl"] = $backUrl;
        $param["source"] = $source;
        $method = "allinpay.yunst.memberService.signContract";
        $yunClient = new yunClient();
        $result = $yunClient->concatUrlParams($method,$param);
        $url = "http://test.allinpay.com/op/gateway?".$result;
        $this->logIns->logMessage("[电子会员签约URL]",Log::INFO,$url);
        header("Location:$url");
    }

    public function signBalanceProtocol($bizUserId,$jumpUrl,$backUrl,$source=2)
    {
        $param = array();
        $yunClient = new yunClient();
        $param["protocolReqSn"] = "TL".date("Ymdhis");
        $param["payerId"] = $bizUserId;
        $param["receiverId"] = "#yunBizUserId_B2C#";
        $param["protocolName"] = "平台测试";
        $param["jumpUrl"] = $jumpUrl;
        $param["backUrl"] = $yunClient->encryptAES($backUrl);
        $param["source"] = $source;
        $method = "allinpay.yunst.memberService.signBalanceProtocol";

        $result = $yunClient->concatUrlParams($method,$param);
        $url = "http://test.allinpay.com/op/gateway?".$result;
        $this->logIns->logMessage("[协议扣款URL]",Log::INFO,$url);
        header("Location:$url");
    }

    /**
     * [setRealName 实名认证]
     */
    public function setRealName($bizUserId,$name,$identityNo)
    {
        $param = array();
        $yunClient = new yunClient();
        $param["bizUserId"] = $bizUserId;
        $param["name"] = $name;
        $param["identityType"] = "1";
        $param["identityNo"] = $yunClient->encryptAES($identityNo);
        $method = "allinpay.yunst.memberService.setRealName";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    /**
     * [getMemberInfo 获取会员信息]
     * @param  [type] $bizUserId [description]
     * @return [type]            [description]
     */
    public function getMemberInfo($bizUserId)
    {
        $param = array();
        $yunClient = new yunClient();
        $param["bizUserId"] = (string)$bizUserId;
        $method = "allinpay.yunst.memberService.getMemberInfo";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    /**
     * [getBankCardBin 查询卡bin]
     */
    public function getBankCardBin($cardNo)
    {
        $param = array();
        $yunClient = new yunClient();
        $param["cardNo"] = $yunClient->encryptAES($cardNo);
        $method = "allinpay.yunst.memberService.getBankCardBin";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    /**
     * [applyBindBankCard 申请绑卡]
     */


    /**
     * [applyBindBankCard 确认绑定银行卡]
     */
    public function bindBankCard($bizUserId,$tranceNum,$phone,$verificationCode,$validate=null,$cvv2=null)
    {
        $param = array();
        $yunClient = new yunClient();
        $param["bizUserId"] = $bizUserId;
        $param["tranceNum"] = $tranceNum;
        $param["phone"] = $phone;
        $param["verificationCode"] = $verificationCode;
        $param["validate"] = $yunClient->encryptAES($validate);
        $param["cvv2"] = $yunClient->encryptAES($cvv2);
        $method = "allinpay.yunst.memberService.bindBankCard";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    /**
     * [queryBankCard 查询绑定银行卡]
     */
    public function queryBankCard($bizUserId)
    {
        $param = array();
        $yunClient = new yunClient();
        $param["bizUserId"] = $bizUserId;
        $method = "allinpay.yunst.memberService.queryBankCard";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    /**
     * [unbindBankCard 解绑绑定银行卡]
     */
    public function unbindBankCard($bizUserId,$cardNo)
    {
        $param = array();
        $yunClient = new yunClient();
        $param["bizUserId"] = $bizUserId;
        $param["cardNo"] = $yunClient->encryptAES($cardNo);
        $method = "allinpay.yunst.memberService.unbindBankCard";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    /**
     * [lockMember 锁定会员]
     */
    public function lockMember($bizUserId)
    {
        $param = array();
        $yunClient = new yunClient();
        $param["bizUserId"] = $bizUserId;
        $method = "allinpay.yunst.memberService.lockMember";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    /**
     * [lockMember 解锁会员]
     */
    public function unlockMember($bizUserId)
    {
        $param = array();
        $yunClient = new yunClient();
        $param["bizUserId"] = $bizUserId;
        $method = "allinpay.yunst.memberService.unlockMember";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    /**
     * [setPayPwd 设置支付密码【密码验证版】]
     */
    public function setPayPwd($bizUserId,$phone,$identityType,$identityNo,$jumpUrl,$backUrl,$name)
    {
        $param = array();
        $yunClient = new yunClient();
        $param["bizUserId"] = $bizUserId;
        $param["phone"] = $phone;
        $param["name"] = $name;
        $param["identityType"] = $identityType;
        $param["identityNo"] = $yunClient->encryptAES($identityNo);
        $param["jumpUrl"] = $jumpUrl;
        $param["backUrl"] = $backUrl;
        $method = "allinpay.yunst.memberService.setPayPwd";
        $result = $yunClient->concatUrlParams($method,$param);
        $url = "http://test.allinpay.com/op/gateway?".$result;
        $this->logIns->logMessage("[设置支付密码【密码验证版】]",Log::INFO,$url);
        header("Location:$url");
    }

    /**
     * [updatePayPwd 修改支付密码【密码验证版】]
     */
    public function updatePayPwd($bizUserId,$name,$identityType,$identityNo,$jumpUrl,$backUrl)
    {
        $param = array();
        $yunClient = new yunClient();
        $param["bizUserId"] = $bizUserId;
        $param["name"] = $name;
        $param["identityType"] = $identityType;
        $param["identityNo"] = $yunClient->encryptAES($identityNo);
        $param["jumpUrl"] = $jumpUrl;
        $param["backUrl"] = $backUrl;
        $method = "allinpay.yunst.memberService.updatePayPwd";
        $result = $yunClient->concatUrlParams($method,$param);
        $url = "http://test.allinpay.com/op/gateway?".$result;
        $this->logIns->logMessage("[修改支付密码【密码验证版】]",Log::INFO,$url);
        header("Location:$url");
    }

    /**
     * [resetPayPwd 重置支付密码【密码验证版】]
     */
    public function resetPayPwd($bizUserId,$name,$phone,$identityType,$identityNo,$jumpUrl,$backUrl)
    {
        $param = array();
        $yunClient = new yunClient();
        $param["bizUserId"] = $bizUserId;
        $param["name"] = $name;
        $param["phone"] = $phone;
        $param["identityType"] = $identityType;
        $param["identityNo"] = $yunClient->encryptAES($identityNo);
        $param["jumpUrl"] = $jumpUrl;
        $param["backUrl"] = $backUrl;
        $method = "allinpay.yunst.memberService.resetPayPwd";
        $result = $yunClient->concatUrlParams($method,$param);
        $url = "http://test.allinpay.com/op/gateway?".$result;
        $this->logIns->logMessage("[重置支付密码【密码验证版】]",Log::INFO,$url);
        header("Location:$url");
    }

    /**
     * [updatePhoneByPayPwd 修改绑定手机【密码验证版】]
     */
    public function updatePhoneByPayPwd($bizUserId,$name,$oldPhone,$identityType,$identityNo,$jumpUrl,$backUrl)
    {
        $param = array();
        $yunClient = new yunClient();
        $param["bizUserId"] = $bizUserId;
        $param["name"] = $name;
        $param["oldPhone"] = $oldPhone;
        $param["identityType"] = $identityType;
        $param["identityNo"] = $yunClient->encryptAES($identityNo);
        $param["jumpUrl"] = $jumpUrl;
        $param["backUrl"] = $backUrl;
        $method = "allinpay.yunst.memberService.updatePhoneByPayPwd";
        $result = $yunClient->concatUrlParams($method,$param);
        $url = "http://test.allinpay.com/op/gateway?".$result;
        $this->logIns->logMessage("[修改绑定手机【密码验证版】]",Log::INFO,$url);
        header("Location:$url");
    }

    /**
     * [applyBindAcct 会员绑定支付账户用户标识]
     */
    public function applyBindAcct($bizUserId,$operationType,$acctType,$acct)
    {
        $param = array();
        $yunClient = new yunClient();
        $param["bizUserId"] = $bizUserId;
        $param["operationType"] = $operationType;
        $param["acctType"] = $acctType;
        $param["acct"] = $acct;
        $method = "allinpay.yunst.memberService.applyBindAcct";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    /**
     * [unbindPhone 解绑手机（验证原手机短信验证码）]
     */
    public function unbindPhone($bizUserId,$phone,$verificationCode)
    {
        $param = array();
        $yunClient = new yunClient();
        $param["bizUserId"] = $bizUserId;
        $param["phone"] = $phone;
        $param["verificationCode"] = $verificationCode;
        $method = "allinpay.yunst.memberService.unbindPhone";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    /**
     * [testdecryptAES 测试AES解密]
     */
    public function testdecryptAES($string)
    {
        $yunClient = new yunClient();
        $result = $yunClient->decryptAES($string);
        var_dump($result);
    }


    public function filebase()
    {
        $file = "data/2222.png";
        $base64_data = base64_encode(file_get_contents($file));
        // $md5file = md5_file($file);
        // var_dump($base64_data);
        // var_dump($md5file);
        return $base64_data;
    }

    public function idcardCollect($bizUserId)
    {
        $param = array();
        $yunClient = new yunClient();
        $param["bizUserId"] = $bizUserId;
        $param["picType"] = 1;
        $param["picture"] = $this->filebase();
        $method = "allinpay.yunst.memberService.idcardCollect";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }
    /******************************************************************************************************************/
    /****                                           订单类                                                        ******/
    /******************************************************************************************************************/


    /**
     * [depositApply 充值申请]
     */
    public function depositApply($bizUserId,$accountSetNo,$amount,$fee,$validateType,$frontUrl,$backUrl,$industryCode,$industryName,$source)
    {

        $yunClient = new yunClient();
        $param["bizOrderNo"] = "TL".date("Ymdhis");
        $param["bizUserId"] = $bizUserId;
        $param["accountSetNo"] = $accountSetNo;
        $param["amount"] = $amount;
        $param["fee"] =$fee;
        $param["validateType"] = $validateType;
        $param["frontUrl"] = $frontUrl;
        $param["backUrl"] = $backUrl;
        //快捷支付
        // $payParam["amount"] = 1;
        // $payParam["bankCardNo"] = $yunClient->encryptAES("6227000267060250071");
        // $payMethod["QUICKPAY_VSP"] = $payParam;
        //收银宝网关
        // $payParam["amount"] = 1;
        // $payParam["paytype"] = "B2C,B2B";
        // $payMethod["GATEWAY_VSP"] = $payParam;
        //微信小程序
        // $payParam["amount"] = 1;
        // $payParam["limitPay"] = "no_credit";
        // $payParam["acct"] = "oUU99wefa2BWRDmoIqUjMTFrxMGY";
        // $payMethod["WECHATPAY_MINIPROGRAM"] = $payParam;
        // 收银宝刷卡支付
        // $payParam["amount"] = 1;
        // $payParam["limitPay"] = "no_credit";
        // $payParam["authcode"] = "oUU99wefa2BWRDmoIqUjMTFrxMGY";
        // $payMethod["CODEPAY_VSP"] = $payParam;
        //收银宝正扫
        // $payParam["amount"] = $amount;
        // $payParam["limitPay"] = "no_credit";
        // $payMethod["SCAN_ALIPAY"] = $payParam;
        // 微信原生小程序
        $payParam["amount"] = 1;
        $payParam["wxAppId"] = "wx806d3df873b1e9fc";
        $payParam["wxMchtId"] = "1550008971";
        $payParam["limitPay"] = "no_credit";
        $payParam["acct"] = "olRPt4pZRC04UilIX8GehfLj-vyI";
        $payParam["cusip"] = "10.168.1.70";
        $payMethod["WECHATPAY_MINIPROGRAM_OPEN"] = $payParam;

        $param["payMethod"] = $payMethod;
        $param["industryCode"] = $industryCode;
        $param["industryName"] = $industryName;
        $param["source"] = $source;
        $method = "allinpay.yunst.orderService.depositApply";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    /**
     * [payByBackSMS 确认支付（后台+短信验证码确认）]
     */
    public function payByBackSMS($bizUserId,$bizOrderNo,$verificationCode,$consumerIp,$tradeNo=null)
    {
        $yunClient = new yunClient();
        $param["bizUserId"] = $bizUserId;
        $param["bizOrderNo"] = $bizOrderNo;
        $param["tradeNo"] = $tradeNo;
        $param["verificationCode"] = $verificationCode;
        $param["consumerIp"] = $consumerIp;
        $method = "allinpay.yunst.orderService.payByBackSMS";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    public function queryReserveFundBalance()
    {
        $yunClient = new yunClient();
        $param["sysid"] = "2002141050372732927";
        $method = "allinpay.yunst.merchantService.queryReserveFundBalance";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }
    /**
     * [payBySMS 确认支付（前台+短信验证码确认）]
     */
    public function payBySMS($bizUserId,$bizOrderNo,$consumerIp,$verificationCode=null)
    {
        $yunClient = new yunClient();
        $param["bizUserId"] = $bizUserId;
        $param["bizOrderNo"] = $bizOrderNo;
        $param["verificationCode"] = $verificationCode;
        $param["consumerIp"] = $consumerIp;
        $method = "allinpay.yunst.orderService.payBySMS";
        $result = $yunClient->concatUrlParams($method,$param);
        $url = "http://test.allinpay.com/op/gateway?".$result;
        $this->logIns->logMessage("[前台+短信验证码确认URL]",Log::INFO,$url);
        //header("Location:$url");
    }

    /**
     * [withdrawApply 提现申请]
     */
    public function withdrawApply($bizUserId,$accountSetNo,$amount,$fee,$validateType,$backUrl,$bankCardNo,$industryCode,$industryName,$source)
    {
        $yunClient = new yunClient();
        $param["bizOrderNo"] = "TL".date("Ymdhis");
        $param["bizUserId"] = $bizUserId;
        $param["accountSetNo"] = $accountSetNo;
        $param["amount"] = $amount;
        $param["fee"] = $fee;
        $param["validateType"] = $validateType;
        $param["backUrl"] = $backUrl;
        $param["withdrawType"] = "D1";
        $param["bankCardNo"] = $yunClient->encryptAES($bankCardNo);
        $param["industryCode"] = $industryCode;
        $param["industryName"] = $industryName;
        $param["source"] = $source;
        $method = "allinpay.yunst.orderService.withdrawApply";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }


    /**
     * [consumeApply 消费申请]
     */
    public function consumeApply($payerId,$recieverId,$amount,$fee,$validateType,$backUrl,$industryCode,$industryName,$source)
    {
        $yunClient = new yunClient();
        $param["payerId"] = $payerId;
        $param["recieverId"] = $recieverId;
        $param["amount"] = $amount;
        $param["fee"] = $fee;
        $param["bizOrderNo"] = "TL".date("Ymdhis");
        $param["validateType"] = $validateType;
        $param["backUrl"] = $backUrl;
        $param["frontUrl"] = "https://www.baidu.com";

        //余额支付 JSONArray
        // $payParam[0]["accountSetNo"]="400193";
        // $payParam[0]["amount"]=$amount;
        // $payMethod["BALANCE"] = $payParam;
        //快捷支付
        // $payParam["amount"] = $amount;
        // $payParam["bankCardNo"] = $yunClient->encryptAES("6227000267060250071");
        // $payMethod["QUICKPAY_VSP"] = $payParam;
        //收银宝网关
        // $payParam["amount"] = 1;
        // $payParam["paytype"] = "B2B";
        // $payMethod["GATEWAY_VSP"] = $payParam;
        //微信小程序
        // $payParam["amount"] = 1;
        // $payParam["limitPay"] = "no_credit";
        // $payParam["acct"] = "oUU99wefa2BWRDmoIqUjMTFrxMGY";
        // $payMethod["WECHATPAY_MINIPROGRAM"] = $payParam;
        // 微信原生小程序
        $payParam["amount"] = 1;
        $payParam["wxAppId"] = "wx806d3df873b1e9fc";
        $payParam["wxMchtId"] = "1550008971";
        $payParam["limitPay"] = "no_credit";
        $payParam["acct"] = "oUU99wefa2BWRDmoIqUjMTFrxMGY";
        $payParam["cusip"] = "10.168.1.70";
        $payMethod["WECHATPAY_MINIPROGRAM_OPEN"] = $payParam;
        // 刷卡支付
        // $payParam["amount"] = $amount;
        // $payParam["limitPay"] = "no_credit";
        // $payParam["authcode"] = "135022012029210261";
        // $payMethod["CODEPAY_VSP"] = $payParam;
        // H5支付
        // $payParam["amount"] = $amount;
        // $payParam["limitPay"] = "no_credit";
        // $payMethod["H5_CASHIER_VSP"] = $payParam;
        // // 二级分账
        // $splitRuleList[0]["bizUserId"]="testtlzf02";
        // $splitRuleList[0]["accountSetNo"]="400193";
        // $splitRuleList[0]["amount"]=1;
        // $splitRuleList[0]["fee"]=0;
        // $splitRuleList[0]["remark"]="消费二级分账";

        // //一级分账
        // $splitParam[0]["bizUserId"]="testtlzf01";
        // $splitParam[0]["accountSetNo"]="400193";
        // $splitParam[0]["amount"]=1;
        // $splitParam[0]["fee"]=0;
        // $splitParam[0]["remark"]="消费一级分账";
        // $splitParam[0]["splitRuleList"]=$splitRuleList;
        // $param["splitRule"] = $splitParam;
        $param["payMethod"] = $payMethod;
        $param["industryCode"] = $industryCode;
        $param["industryName"] = $industryName;
        $param["source"] = $source;
        $method = "allinpay.yunst.orderService.consumeApply";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    /**
     * [agentCollectApply 托管代收]
     */
    public function agentCollectApply($payerId,$tradeCode,$amount,$fee,$backUrl,$validateType,$industryCode,$industryName,$source)
    {
        $yunClient = new yunClient();
        $param["bizOrderNo"] = "TL".date("Ymdhis");
        $param["payerId"] = $payerId;
        //收款列表 JSONArray
        $recievParam[0]["bizUserId"]="testtlzf02";
        $recievParam[0]["amount"]=$amount;
        $param["recieverList"] = $recievParam;
        $param["tradeCode"] = $tradeCode;
        $param["amount"] = $amount;
        $param["fee"] = $fee;
        $param["backUrl"] = $backUrl;
        $param["validateType"] = $validateType;
        //余额支付 JSONArray
        $payParam[0]["accountSetNo"]="400193";
        $payParam[0]["amount"]=$amount;
        $payMethod["BALANCE"] = $payParam;
        //快捷支付
        // $payParam["amount"] = $amount;
        // $payParam["bankCardNo"] = $yunClient->encryptAES("6227000267060250071");
        // $payMethod["QUICKPAY_VSP"] = $payParam;
        //收银宝网关
        // $payParam["amount"] = 1;
        // $payParam["paytype"] = "B2B";
        // $payMethod["GATEWAY_VSP"] = $payParam;
        //微信小程序
        // $payParam["amount"] = 1;
        // $payParam["limitPay"] = "no_credit";
        // $payParam["acct"] = "oUU99wefa2BWRDmoIqUjMTFrxMGY";
        // $payMethod["WECHATPAY_MINIPROGRAM"] = $payParam;
        $param["payMethod"] = $payMethod;
        $param["industryCode"] = $industryCode;
        $param["industryName"] = $industryName;
        $param["source"] = $source;
        $method = "allinpay.yunst.orderService.agentCollectApply";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    /**
     * [signalAgentPay 单笔托管代付]
     */
    public function signalAgentPay($bizUserId,$bizOrderNo,$tradeCode,$amount,$fee,$backUrl)
    {
        $yunClient = new yunClient();
        $param["bizOrderNo"] = "TL".date("Ymdhis");
        //托管代收中的付款人列表
        $collectPayList[0]["bizOrderNo"] = $bizOrderNo;
        $collectPayList[0]["amount"] = 3;
        $param["collectPayList"] = $collectPayList;
        //收款账户bizUserId
        $param["bizUserId"] = $bizUserId;

        $splitParam[0]["bizUserId"]="ORGCASH30003";
        $splitParam[0]["accountSetNo"]="400193";
        $splitParam[0]["amount"]=1;
        $splitParam[0]["fee"]=0;
        $splitParam[0]["remark"]="消费一级分账";
        $param["splitRuleList"] = $splitParam;
        //
        $param["accountSetNo"] = "400193";
        $param["tradeCode"] = $tradeCode;
        $param["amount"] = 3;
        $param["fee"] = 0;
        $param["backUrl"] = $backUrl;
        $method = "allinpay.yunst.orderService.signalAgentPay";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    public function batchAgentPay()
    {
        $yunClient = new yunClient();
        $param["bizBatchNo"] = "1596708057721ba";
        //托管代收中的付款人列表
        // $collectPayList1[0]["bizOrderNo"] = "TL20200806044959";
        // $collectPayList1[0]["amount"] = 3;
        // $batchPayList[0]["bizOrderNo"] = "BatchTL111111111";
        // $batchPayList[0]["bizUserId"] = "testtlzf01";
        // $batchPayList[0]["accountSetNo"] = "400193";
        // $batchPayList[0]["collectPayList"] = $collectPayList1;
        // $batchPayList[0]["backUrl"] = "https://www.baidu.com";
        // $batchPayList[0]["amount"] = 3;
        // $batchPayList[0]["fee"] = 0;

        // $collectPayList2[0]["bizOrderNo"] = "TL20200806045405";
        // $collectPayList2[0]["amount"] = 2;
        // $batchPayList[1]["bizOrderNo"] = "BatchTL2222222222";
        // $batchPayList[1]["bizUserId"] = "testtlzf02";
        // $batchPayList[1]["accountSetNo"] = "400193";
        // $batchPayList[1]["collectPayList"] = $collectPayList2;
        // $batchPayList[1]["backUrl"] = "https://www.baidu.com";
        // $batchPayList[1]["amount"] = 2;
        // $batchPayList[1]["fee"] = 0;
        //
        $collectPayList1[0]["bizOrderNo"] = "1596695571119ds";
        $collectPayList1[0]["amount"] = 2;
        $batchPayList[0]["bizOrderNo"] = "1596700984548lyz";
        $batchPayList[0]["bizUserId"] = "ORGCASH30001";
        $batchPayList[0]["accountSetNo"] = "400193";
        $batchPayList[0]["collectPayList"] = $collectPayList1;
        $batchPayList[0]["backUrl"] = "https://www.baidu.com";
        $batchPayList[0]["amount"] = 2;
        $batchPayList[0]["fee"] = 0;
        $splitRuleparam[0]["accountSetNo"] = "400193";
        $splitRuleparam[0]["amount"] = 2;
        $splitRuleparam[0]["bizUserId"] = "f7229622-1dfd-4444-a018-6daece0203d6";
        $splitRuleparam[0]["fee"] = 0;
        $splitRuleparam[0]["remark"] = " 消费一级分账";
        $batchPayList[0]["splitRuleList"] = $splitRuleparam;

        $collectPayList2[0]["bizOrderNo"] = "1596695643171ds";
        $collectPayList2[0]["amount"] = 2;
        $batchPayList[1]["bizOrderNo"] = "1596700984549lyz";
        $batchPayList[1]["bizUserId"] = "ORGCASH30001";
        $batchPayList[1]["accountSetNo"] = "400193";
        $batchPayList[1]["collectPayList"] = $collectPayList2;
        $batchPayList[1]["backUrl"] = "https://www.baidu.com";
        $batchPayList[1]["amount"] = 2;
        $batchPayList[1]["fee"] = 0;
        $splitRuleparam1[0]["accountSetNo"] = "400193";
        $splitRuleparam1[0]["amount"] = 2;
        $splitRuleparam1[0]["bizUserId"] = "f7229622-1dfd-4444-a018-6daece0203d6";
        $splitRuleparam1[0]["fee"] = 0;
        $splitRuleparam1[0]["remark"] = " 消费一级分账";
        $batchPayList[1]["splitRuleList"] = $splitRuleparam1;



        $param["batchPayList"] = $batchPayList;
        //收款账户bizUserId
        $param["tradeCode"] = "4001";
        $method = "allinpay.yunst.orderService.batchAgentPay";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    /**
     * [freezeMoney 冻结金额]
     */
    public function freezeMoney($bizUserId,$amount)
    {
        $yunClient = new yunClient();
        $param["bizFreezenNo"] = "TL".date("Ymdhis");
        $param["bizUserId"] = $bizUserId;
        $param["accountSetNo"] = "400193";
        $param["amount"] = $amount;
        $method = "allinpay.yunst.orderService.freezeMoney";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    /**
     * [unfreezeMoney 解冻金额]
     */
    public function unfreezeMoney($bizUserId,$bizFreezenNo,$amount)
    {
        $yunClient = new yunClient();
        $param["bizFreezenNo"] = $bizFreezenNo;
        $param["bizUserId"] = $bizUserId;
        $param["accountSetNo"] = "400193";
        $param["amount"] = $amount;
        $method = "allinpay.yunst.orderService.unfreezeMoney";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    /**
     * [refund 退款申请]
     */
    public function refund($oriBizOrderNo,$bizUserId,$refundType,$amount,$backUrl)
    {
        $yunClient = new yunClient();
        $param["bizOrderNo"] = "TL".date("Ymdhis");
        $param["oriBizOrderNo"] = $oriBizOrderNo;
        $param["bizUserId"] = $bizUserId;
        $param["refundType"] = $refundType;
        $param["amount"] = $amount;
        $param["backUrl"] = $backUrl;
        $method = "allinpay.yunst.orderService.refund";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    /**
     * [applicationTransfer 平台转账]
     */
    public function applicationTransfer($targetBizUserId,$amount)
    {
        $yunClient = new yunClient();
        $param["bizTransferNo"] = "TL".date("Ymdhis");
        $param["sourceAccountSetNo"] = "100001";
        $param["targetBizUserId"] = $targetBizUserId;
        $param["targetAccountSetNo"] = "400193";
        $param["amount"] = $amount;
        $param["backUrl"] = "https://www.baidu.com";
        $method = "allinpay.yunst.orderService.applicationTransfer";
        $result = $yunClient->request($method,$param);
        var_dump($result);

    }

    /**
     * [queryBalance 查询余额]
     */
    public function queryBalance($bizUserId,$accountSetNo)
    {
        $yunClient = new yunClient();
        $param["bizUserId"] = $bizUserId;
        $param["accountSetNo"] = $accountSetNo;
        $method = "allinpay.yunst.orderService.queryBalance";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    public function queryMerchantBalance($accountSetNo)
    {
        $yunClient = new yunClient();
        $param["accountSetNo"] = $accountSetNo;
        $method = "allinpay.yunst.merchantService.queryMerchantBalance";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    /**
     * [getOrderDetail 查询订单状态]
     */
    public function getOrderDetail($bizOrderNo)
    {
        $yunClient = new yunClient();
        $param["bizOrderNo"] = $bizOrderNo;
        $method = "allinpay.yunst.orderService.getOrderDetail";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    /**
     * [queryInExpDetail 查询账户收支明细]
     */
    public function queryInExpDetail($timestart,$timeend,$bizUserId,$accountSetNo,$startPosition,$queryNum)
    {
        $yunClient = new yunClient();
        $param["bizUserId"] = $bizUserId;
        $param["accountSetNo"] = $accountSetNo;
        $param["dateStart"] = date("Y-m-d",strtotime($timestart));
        $param["dateEnd"] = date("Y-m-d",strtotime($timeend));
        $param["startPosition"] = $startPosition;
        $param["queryNum"] = $queryNum;
        $method = "allinpay.yunst.orderService.queryInExpDetail";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    /**
     * [getCheckAccountFile 平台集合对账下载]
     */
    public function getCheckAccountFile($timestart,$fileType)
    {
        $yunClient = new yunClient();
        $param["date"] = date("Ymd",strtotime($timestart));
        $param["fileType"] = $fileType;
        $method = "allinpay.yunst.orderService.getCheckAccountFile";
        $result = $yunClient->request($method,$param);
        set_time_limit(0);
        $file = file_get_contents($url);
        file_put_contents("./DownFile/$data.txt", $file);
    }

    public function agentCollectProtocolApply($bizUserId,$protocolNo)
    {
        $yunClient = new yunClient();
        $param["payerId"] = $bizUserId;
        $param["protocolNo"] = $protocolNo;
        $param["tradeCode"] = "3001";
        $param["amount"] = 1;
        $param["backUrl"] = "https://www.baidu.com";
        $param["industryCode"] = $queryNum;
        $param["industryName"] = $queryNum;
        $param["source"] = "2";
        $method = "allinpay.yunst.orderService.queryInExpDetail";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    public function withdrawApply_HT()
    {
        $yunClient = new yunClient();
        $param["bizOrderNo"] = "TL".date("Ymdhis");
        $param["bizUserId"] = "1294229449063051265";
        $param["accountSetNo"] = "400193";
        $param["amount"] = 1;
        $param["validateType"] = 0;
        $param["backUrl"] = "https://www.baidu.com";
        $param["bankCardNo"] = $yunClient->encryptAES("6217002870069115069");
        $param["withdrawType"] = "D0";
        //$param["bankCardPro"] = 1;
        $param["fee"] =0;
        $param["industryCode"] = "1413";
        $param["industryName"] = "汽车售后";
        $param["source"] = 2;

        $payparam["subAcctNo"] = "9120001009798353840";
        $payparam["PAYEE_ACCT_NO"] = "6217002870069115069";
        $payparam["PAYEE_ACCT_NAME"] = "测试";
        $payparam["AMOUNT"] = "1";
        $payparam["SUMMARY"] = "佣金提现";
        $Htarray = array();
        $Htarray['PAYEE_ACCT_NO'] = "6217002870069115069";
        $Htarray['PAYEE_ACCT_NAME'] = "测试";
        $Htarray['AMOUNT'] = "1";
        $Htarray["SUMMARY"] = "佣金提现";
        ksort($Htarray);
        $json = json_encode($Htarray,JSON_UNESCAPED_UNICODE);
        $payparam["SIGNED_MSG_MER"] = $yunClient->htBankWithdrawSign($json);
        $payMethod["WITHDRAW_HTBANK"] = $payparam;
        $param["payMethod"] = $payMethod;
        $method = "allinpay.yunst.orderService.withdrawApply";
        $result = $yunClient->request($method,$param);
        var_dump($result);
    }

    /******************************************************************************************************************/
    /****                                           工具类                                                        ******/
    /******************************************************************************************************************/
    /**
     *请求封装
     */
    public  function request($method,$param)
    {
        $request["appId"] = $this->config->getConf('appId');
        $request["method"] = $method;
        $request["charset"] = "utf-8";
        $request["format"] = "JSON";
        $request["signType"] = "SHA256WithRSA";
        $request["timestamp"] = date("Y-m-d H:i:s", time());
        $request["version"] = $this->config->getConf('version');
        $request["bizContent"] = json_encode($param,JSON_UNESCAPED_UNICODE);
        $request["sign"] = $this->sign($request);
        $serverAddress =$this->config->getConf('serverUrl');
        $result = $this->requestYSTAPI($serverAddress, $request);
        return $this->checkResult($result);
    }

    /**
     * [concatUrlParams 请求链接拼装]
     */
    public  function concatUrlParams($method,$param)
    {
        $request = [];
        $sb = '';
        $request["appId"] = $this->config->getConf('appId');
        $request["method"] = $method;
        $request["charset"] = "utf-8";
        $request["format"] = "JSON";
        $request["signType"] = "SHA256WithRSA";
        $request["timestamp"] = date("Y-m-d H:i:s", time());
        $request["version"] = $this->config->getConf('version');
        $request["bizContent"] = json_encode($param);
        $request["sign"] = $this->sign($request);
        foreach ($request as $entry_key => $entry_value) {
            $sb .= $entry_key . '=' . urlencode($entry_value) . '&';
        }
        $sb = trim($sb, "&");
        return $sb;

    }

    /**
     * [sign 开放平台签名算法]
     */
    public function sign($strRequest)
    {
        unset($strRequest['signType']);
        $strRequest = array_filter($strRequest);//剔除值为空的参数
        ksort($strRequest);
        $sb = '';
        foreach ($strRequest as $entry_key => $entry_value) {
            $sb .= $entry_key . '=' . $entry_value . '&';
        }
        $sb = trim($sb, "&");
        $this->logIns->logMessage("[待签名源串]",Log::INFO,$sb);
        //MD5摘要计算,Base64
        $sb = base64_encode(hash('md5', $sb, true));
        $privateKey = $this->getPrivateKey();
        print_r($privateKey);
        if (openssl_sign(utf8_encode($sb), $sign, $privateKey, OPENSSL_ALGO_SHA256)) {//SHA256withRSA密钥加签
            openssl_free_key($privateKey);
            $sign = base64_encode($sign);
            return $sign;
        } else {
            echo "sign error";
            exit();
        }
    }

    /**
     *获取私匙的绝对路径;
     */
    public function getPrivateKey()
    {

        return $this->loadPrivateKey($this->config->getConf('path'),$this->config->getConf('pwd'));
    }

    /**
     * 从证书文件中装入私钥 pem格式;
     */
    private function loadPrivateKey($path, $pwd)
    {

        $str = explode('.', $path);
        $houzuiName = $str[count($str) - 1];
        if ($houzuiName == "pfx") {
            return $this->loadPrivateKeyByPfx($path, $pwd);
        }

        if ($houzuiName == "pem") {
            $priKey = file_get_contents($path);
            $res = openssl_get_privatekey($priKey, $pwd);
            //print_r($res);
            if (!$res) {
                exit('您使用的私钥格式错误，请检查私钥配置');
            }
            return $res;
        }
    }

    /**
     * 从证书文件中装入私钥 Pfx 文件格式
     */
    private function loadPrivateKeyByPfx($path, $pwd)
    {
        if (file_exists($path)) {
            $priKey = file_get_contents($path);
            if (openssl_pkcs12_read($priKey, $certs, $pwd)) {
                $privateKey = $certs['pkey'];
                //print_r($privateKey);
                return $privateKey;

            }
            die("私钥文件格式错误");

        }
        die('私钥文件不存在');
    }

    /**
     *请求云商通
     */
    private function requestYSTAPI($serverUrl, $args)
    {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $serverUrl);

        $sb = '';
        $reqbody = array();
        foreach ($args as $entry_key => $entry_value) {
            $sb .= $entry_key . '=' . urlencode($entry_value) . '&';
        }
        $sb = trim($sb, "&");
        $this->logIns->logMessage("[请求body]",Log::INFO,$sb);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $sb);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-length', count($reqbody)));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        $result = curl_exec($ch);
        $info = curl_getinfo($ch);
        $this->logIns->logMessage("[请求状态]",Log::INFO,json_encode($info));
        curl_close($ch);
        $this->logIns->logMessage("[请求返回]",Log::INFO,$result);
        return $result;
    }

    /**
     *检查返回的结果是否合法;
     */
    private function checkResult($result)
    {
        $arr = json_decode($result,true);
        $sign = $arr['sign'];
        unset($arr['sign']);
        $this->Asciisort($arr);
        print_r($arr);
        $str = json_encode($arr, JSON_UNESCAPED_UNICODE|JSON_FORCE_OBJECT|JSON_UNESCAPED_SLASHES);
        //$str = stripslashes($str);
        print_r($str);
        $this->logIns->logMessage("[待验签字段]",Log::INFO,$str);
        $success = false;
        if ($sign != null) {
            $success = $this->verify($this->getPublicKeyPath(),$str,base64_decode($sign));
        }
        if ($success) {
            return $arr;
        }
        return $success;
    }

    /**
     * [foo 对返回数据按照第一个字符的键值ASCII码递增排序]
     */
    public function Asciisort(&$ar) {
        if(is_array($ar)) {
            ksort($ar);
            foreach($ar as &$v) $this->Asciisort($v);
        }
    }
    /**
     *验证返回的数据的合法性
     */
    private function verify($publicKeyPath, $text, $sign)
    {
        //MD5摘要计算
        $text = base64_encode(hash('md5', $text, true));
        $pubKeyId = openssl_get_publickey(file_get_contents($publicKeyPath));
        $flag = (bool) openssl_verify($text, $sign, $pubKeyId, "sha256WithRSAEncryption");
        openssl_free_key($pubKeyId);
        $this->logIns->logMessage("[sign value]",Log::INFO, (bool)($flag));
        return $flag;
    }

    /**
     *获取公匙的绝对路径
     */
    public function getPublicKeyPath()
    {
        return $this->config->getConf('tlCertPath');
    }

    /**
     * [encryptAES AES-SHA1PRNG加密算法]
     */
    public function encryptAES($string){
        //AES加密通过SHA1PRNG算法
        $key = substr(openssl_digest(openssl_digest($this->config->getConf('secretKey'), 'sha1', true), 'sha1', true), 0, 16);
        $data = openssl_encrypt($string, 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
        $data = strtoupper(bin2hex($data));
        return $data;
    }

    /**
     * [encryptAES AES-SHA1PRNG解密算法]
     */
    public function decryptAES($string)
    {
        $key = substr(openssl_digest(openssl_digest($this->config->getConf('secretKey'), 'sha1', true), 'sha1', true), 0, 16);
        $decrypted = openssl_decrypt(hex2bin($string), 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
        return $decrypted;
    }
    public function htBankWithdrawSign($text){
        $htCertPath = $this->config->getConf('htCertPath');
        $htCertPwd = $this->config->getConf('htCertPwd');
        $htPriKey = $this->loadPrivateKeyByPfx($htCertPath,$htCertPwd);
        openssl_sign($text, $sign, $htPriKey);
        openssl_free_key($htPriKey);
        $sign = base64_encode($sign);
        return $sign;
    }

}